<?php require VIEWPATH . ADMIN_DIR . DIRECTORY_SEPARATOR . 'header.php' ?>
<style>
	.outer-schedule {
		display: flex;
		justify-content: center;
		margin-right: 80px;
		margin-bottom: 20px;
	}
	.items {
		display: flex;
		flex-wrap: wrap;
		width: 900px;
		text-align: center;
		cursor: pointer;
	}
	.item {
		border: 1px solid #EDEDED;
		background: #F8FAFE;
		box-sizing: border-box;
		width: 225px;
		padding-top: 10px;
	}
	.item > div {
		margin-top: 5px;
	}
	.btn-edit {
		text-align: right;
	}
	.sign-time {
		color: #428BCA;
		padding-left: 5px;
	}
	.hour-input {
		width: 80px;
	}
	.items-schedule .item .sign-time-empty, .refresh {
		padding-right: 70px;
	}
	.displaynone {
		display: none;
	}

	.outer-submit {
		display: flex;
		justify-content: center;
		margin-right: 80px;
		margin-bottom: 20px;
		/* text-align: right; */
	}
	.div-submit {
		margin-top: 20px;
		width: 900px;
		text-align: right;
	}
</style>
<div class="page-header">
    <h1 style="font-size: 20px;">
        <a class="a-back" href="<?= admin_url('data/recipe') ?>">
            <i class="fa fa-reply"></i>
        </a>
        <?php if(isset($recipeId)): ?>
        修改食谱
        <?php else: ?>
        添加食谱
        <?php endif ?>
    </h1>
</div>
<div class="col-xs-12">
    <div id="schedule-form" class="form-horizontal">
        <!-- 课程模板id -->
        <input type="hidden" name="id" value="<?= isset($recipeId) ? $recipeId : '' ?>" />
        <div class="form-group">
            <label class="col-sm-3 control-label no-padding-right">食谱名称：</label>
            <div class="col-sm-6">
				<input class="form-control" name="title" 
                    value="<?= isset($recipe['title']) ? $recipe['title'] : '学校食谱' . date('Ymd') ?>"
                    placeholder="模板标题" />
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label no-padding-right">菜品分类：</label>
            <div class="col-sm-6">
                <select class="chosen-select form-control tag-input-style" id="cate-select" data-placeholder="选择菜品分类" name="cate" multiple="multiple">
                    <?php foreach($cateList as $cate): ?>
                        <option value="<?=$cate['id']?>"><?=$cate['title']?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="form-group">
				<label class="col-sm-3 control-label no-padding-right">发布班级：</label>
				<div class="col-sm-6">
					<?php foreach($gradeArray as $key => $grade): ?>
						<div class="well well-sm">
							<a class="blue select-grade" href="javascript:;" title="全选年级"><?=$key?> <span style="color: #999;margin-left: 5px">(点击选中全部班级)</span></a>
							<div class="mt5">
							<?php foreach($grade['class'] as $class): ?>
								<label class="inline checkbox-item mr20">
									<input class="ace" type="checkbox" name="recipe_class" value="<?=$class['id']?>" />
									<span class="lbl"> <?=$class['class_name']?></span>
								</label>
							<?php endforeach; ?>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
        <div class="form-group">
            <label class="col-sm-3 control-label no-padding-right">菜品时段：</label>
            <div class="col-sm-6">
					<div class="btn btn-info" id="increase-schedule">添加时段</div>
					&nbsp;&nbsp;
					<div class="btn btn-danger" id="decrease-schedule">删除时段</div>
            </div>
        </div>
        <?php if(isset($recipe['timeArr']) && !empty($recipe['timeArr'])): ?>
            <div class="outer-schedule">
                <div class="items items-schedule">
                    <?php foreach($recipe['timeArr'] as $key => $time): ?>
                        <div class="item item-<?= $key + 1 ?>" href="#modal-schedule" data-toggle="modal">
                            <div>第<span class="timeslot"><?= $key + 1 ?></span>时段</div>
                            <div>用餐时间：<span class="begin_time"><?= $time['begin_time'] ?></span>&nbsp;&nbsp;-&nbsp;&nbsp;<span class="end_time"><?= $time['end_time'] ?></span></div>
                            <div class="btn-edit"><i class="fa fa-pencil blue"></i>&nbsp;&nbsp;</div>
                        </div>
                    <?php endforeach ?>
                </div>
            </div>	
        <?php else: ?>
            <div class="outer-schedule">
                <div class="items items-schedule">
                    <div class="item item-1" data-interval="10" href="#modal-schedule" data-toggle="modal">
                        <div>第<span class="timeslot">1</span>时段</div>
                        <div>用餐时间：<span class="begin_time">10:00</span>&nbsp;&nbsp;-&nbsp;&nbsp;<span class="end_time">14:00</span></div>
                        <div class="btn-edit"><i class="fa fa-pencil blue"></i>&nbsp;&nbsp;</div>
                    </div>
                    <div class="item item-2" data-interval="10" href="#modal-schedule" data-toggle="modal">
                        <div>第<span class="timeslot">2</span>时段</div>
                        <div>用餐时间：<span class="begin_time">17:00</span>&nbsp;&nbsp;-&nbsp;&nbsp;<span class="end_time">20:00</span></div>
                        <div class="btn-edit"><i class="fa fa-pencil blue"></i>&nbsp;&nbsp;</div>
                    </div>
                    <div class="item item-3" data-interval="10" href="#modal-schedule" data-toggle="modal">
                        <div>第<span class="timeslot">3</span>时段</div>
                        <div>用餐时间：<span class="begin_time">21:00</span>&nbsp;&nbsp;-&nbsp;&nbsp;<span class="end_time">23:00</span></div>
                        <div class="btn-edit"><i class="fa fa-pencil blue"></i>&nbsp;&nbsp;</div>
                    </div>
                </div>
            </div>	
		<?php endif ?>
		<div class="outer-submit">
			<div class="clearfix2 div-submit">
				<button class="btn btn-info" id="save-schedule-action">
					<i class="ace-icon fa fa-check"></i> 提交
				</button>
			</div>
		</div>

	</div>
</div>
<!-- 编辑用餐时间弹窗 -->
<div id="modal-schedule" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header no-padding">
				<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button> <span id="school-name"></span>
					编辑第<span class="timeslot"></span>节
				</div>
			</div>
			<div class="modal-body no-padding">
				<div class="row">
					<div class="col-xs-12">
						<form class="form-horizontal mt10">
							<div class="form-group">
								<label class="col-sm-3 control-label no-padding-right">用餐时间：</label>
								<div class="col-sm-6">
									<input class="hour-input hour-input-begin" type="text" name="begin_time" value=""/>
									&nbsp;&nbsp;-&nbsp;&nbsp;
									<input class="hour-input hour-input-end" type="text" name="end_time" value=""/>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<div class="modal-footer no-margin-top" >
				<a href="javascript:;" class="btn btn-sm btn-primary" id="save-schedule" data-dismiss="modal" aria-hidden="true">
					<i class="ace-icon fa fa-check"></i> 确认
				</a>
			</div>
		</div>
	</div>
</div>
<?php require VIEWPATH. ADMIN_DIR. DIRECTORY_SEPARATOR. 'footer.php'?>
<!-- 使用新的datetimepicker.js和css，解决设置不了pickerPosition -->
<link rel="stylesheet" href="<?=$staticAdminUrl?>assets/css/bootstrap-datetimepicker-new.min.css" />
<script src="<?=$staticAdminUrl?>assets/js/bootstrap-datetimepicker-new.min.js"></script>
<script type="text/javascript">
var table = "";
$(function() {
    <?php if(isset($recipe) && !empty($recipe)): ?>
        // 选中接收的班级
        var classArray = "<?=$recipe['class_id']?>".split(",");
        for(var i in classArray) {
            var classRecipe = $("[name=recipe_class][value="+ classArray[i] +"]")[0];
            if(classRecipe) {
                classRecipe.checked = true;
            }
        }
        // 选中菜品分类
        var cateIdArr = "<?= $recipe['cate'] ?>".split(",");
        // console.log(cateIdArr);
        for(var i in cateIdArr) {
            $("[name=cate] [value="+ cateIdArr[i] +"]").attr("selected", "selected");
        }
    <?php endif; ?>
    // 菜品分类下拉选择
    $("#cate-select").chosen({
        search_contains: true
    }); 
    $("#cate-select").trigger("liszt:updated");

    var div = $(".items-schedule");
    // 添加节数
    $("#increase-schedule").click(function() {
        // 当前节数
        var count = $('.items-schedule .item').length;
        // 下一节数
        var next = count + 1;
        div.append('<div class="item item-' + next + '" data-interval="10" href="#modal-schedule" data-toggle="modal">\
			<div>第<span class="timeslot">' + next + '</span>时段</div>\
			<div>用餐时间：<span class="begin_time">21:00</span>&nbsp;&nbsp;-&nbsp;&nbsp;<span class="end_time">23:00</span></div>\
			<div class="btn-edit"><i class="fa fa-pencil blue"></i>&nbsp;&nbsp;</div>\
		</div>');
    });
    // 删除节数
    $("#decrease-schedule").click(function() {
        $('.items-schedule .item:last').remove();
    });

    $('.hour-input-begin').timepicker({
        minuteStep: 1,
        showSeconds: false,
        showMeridian: false,
        disableFocus: true,
        icons: {
            up: 'fa fa-chevron-up',
            down: 'fa fa-chevron-down'
        }
    }).on('changeTime.timepicker', function(e) {
        var interval = $("[name=sign_interval]").val();
        var signBeginTime = subtract_time($(this).val(), interval);
        var value = e.time.value ;
        var arr = value.split(':');
        if(arr[0] < 10) {
            $(this).val('0' + e.time.value);
        }
        $("#modal-schedule").find(".sign_begin_time").text(signBeginTime);
        $("#modal-schedule").find(".sign_end_time").text($(this).val());
    });
    $('.hour-input-end').timepicker({
        minuteStep: 1,
        showSeconds: false,
        showMeridian: false,
        disableFocus: true,
        icons: {
            up: 'fa fa-chevron-up',
            down: 'fa fa-chevron-down'
        }
    }).on('changeTime.timepicker', function(e) {
        var value = e.time.value ;
        var arr = value.split(':');
        if(arr[0] < 10) {
            $(this).val('0' + e.time.value);
        }
    });									

	// 点击编辑
	$("body").on("click", ".items-schedule .item", function() {
		var signInterval = $(this).data('interval');
		if(signInterval == 0) {
			$("#modal-schedule").find(".sign-time-not-empty").hide();
			$("#modal-schedule").find(".sign-time-empty").show();
		} else {
			$("#modal-schedule").find(".sign-time-empty").hide();
			$("#modal-schedule").find(".sign-time-not-empty").show();
		}
		var modal = $("#modal-schedule");
		modal.find(".timeslot").html($(this).find(".timeslot").html());
		modal.find("[name=begin_time]").val($(this).find(".begin_time").html());
		modal.find("[name=end_time]").val($(this).find(".end_time").html());
		modal.find(".sign_begin_time").html($(this).find(".sign_begin_time").html());
		modal.find(".sign_end_time").html($(this).find(".sign_end_time").html());
		modal.find("[name=sign_interval]").val(signInterval);
		modal.find("[name=refresh]").val($(this).find(".refresh").html());
	});
	// 实时监听interval变化
	$("[name=sign_interval]").on("input propertychange", function(){
		// 计算interval最大值
		var beginTime = $("#modal-schedule").find("[name=begin_time]").val();
		var $timeArr = beginTime.split(":");
		var $hour = parseInt($timeArr[0]);
		var $min = parseInt($timeArr[1]);
		// 总共多少分钟
		var $minCount = $hour * 60 + $min;
		
		if($(this).val() > $minCount) {
			$("[name=sign_interval]").val($minCount);
		}
		if($(this).val() < 0) {
			// tips_alert("不能小于0", false, function() {
				$("[name=sign_interval]").val(10);
			// });
			// return;
		}
		if($(this).val() == 0) {
			$("#modal-schedule").find(".sign-time-not-empty").hide();
			$("#modal-schedule").find(".sign-time-empty").show();
		} else {
			$("#modal-schedule").find(".sign-time-empty").hide();
			$("#modal-schedule").find(".sign-time-not-empty").show();
			var beginTime = $("#modal-schedule").find("[name=begin_time]").val();
			var signBeginTime = subtract_time(beginTime, $(this).val());
			$("#modal-schedule").find(".sign_begin_time").text(signBeginTime);
			$("#modal-schedule").find(".sign_end_time").text(beginTime);
		}
	});
	// 监听上课开始时间变化
	$("[name=begin_time]").on("input propertychange", function(){
		// alert($(this).val());
		var interval = $("[name=sign_interval]").val();
		var signBeginTime = subtract_time($(this).val(), interval);
		$("#modal-schedule").find(".sign_begin_time").text(signBeginTime);
		$("#modal-schedule").find(".sign_end_time").text($(this).val());
	});

	// 保存弹窗
	$("#save-schedule").click(function(){
		var modal = $("#modal-schedule");
		var timeslot = modal.find(".timeslot").html();
		var beginTime = modal.find("[name=begin_time]").val();
		var endTime = modal.find("[name=end_time]").val();
		var item = $(".items-schedule").find(".item-" + timeslot);
		// console.log(item.length);
		item.find(".begin_time").html(beginTime);
		item.find(".end_time").html(endTime);
	});
	// 保存数据
	$("#save-schedule-action").click(function(){
		var submitUrl = "<?=admin_url('data/save_recipe_action')?>";
		var timeArr = [];
		$(".items-schedule .item").each(function(){
			timeArr.push({
				'begin_time': $(this).find(".begin_time").html(),
				'end_time': $(this).find(".end_time").html(),
			});
		});
		// console.log(timeArr);
        // 发布班级
        var recipeClassArr = [];
        $("[name=recipe_class]").each(function() {
            if($(this).prop("checked")) {
                recipeClassArr.push($(this).val());
            }
        });
        var recipeClass = recipeClassArr.join(',');
        // 菜品分类
        var cate = $("[name=cate]").val();
		var data = {
			"id": $("[name=id]").val(),
			"title": $("[name=title]").val(),
			"time_arr": timeArr,
            "recipe_class": recipeClass,
            "cate": cate
		};
		ajax_post(submitUrl, data, function(res) {
			if (res.success) {
				window.location.href = "<?=admin_url('data/recipe') ?>";
			}
		});
	});

    // 点击年级，全选下级班级
    var cancel = false;
    $(".select-grade").click(function(){
        // 第一选择，第二次取消选择
        if(cancel) {
            // 取消选择
            $(this).parent().find("[name=recipe_class]").each(function(){
                $(this)[0].checked = false;
            });
            cancel = ! cancel;
        } else {
            // 选择
            $(this).parent().find("[name=recipe_class]").each(function(){
                $(this)[0].checked = true;
            });
            cancel = ! cancel;
        }
    })
})
// 某时间点前移多少分钟，格式‘09:00’
function subtract_time($time, $offset) {
	var $timeArr = $time.split(":");
	var $hour = parseInt($timeArr[0]);
	var $min = parseInt($timeArr[1]);
	// 总共多少分钟
	var $minCount = $hour * 60 + $min;
	var $minCountNew = $minCount - $offset;
	if($minCountNew <= 0) {
		return "00:00";
	}
	var $hourNew = Math.floor($minCountNew / 60);

	var $minNew = $minCountNew % 60;
	// console.log($minNew);
	if($minNew < 10) {
		$minNew = '0' + $minNew;
	}
	if($hourNew < 10) {
		$hourNew = '0' + $hourNew;
	}
	return $hourNew + ':' + $minNew;
}
</script>